package com.mz.mattress.client.service.impl;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.mz.mattress.api.enums.OrderTagEnum;
import com.mz.mattress.api.util.IdUtil;
import com.mz.mattress.client.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Service
@Slf4j
public class WxPayProcess {

    @Autowired
    private OrderService orderService;

    /**
     * 支付回调
     * @param request
     * @return
     */
    public String payCallback(HttpServletRequest request, String orderId) {

        WxPayOrderNotifyResult result = parseParams(request);

//        String orderId = result.getOutTradeNo();

        OrderTagEnum orderTag = IdUtil.getOrderTag(orderId);
        if (orderTag == OrderTagEnum.mattressOrder) {
            orderService.payNotify(result, orderId);
        }

        return "ok";
    }

    /**
     * 退款回调
     * @param request
     * @return
     */
    public String refundCallback(HttpServletRequest request, String orderId) {

        WxPayOrderNotifyResult result = parseParams(request);

//        String orderId = result.getOutTradeNo();

        OrderTagEnum orderTag = IdUtil.getOrderTag(orderId);
        if (orderTag == OrderTagEnum.mattressOrderRefund) {
//            orderService.refundNotify(result, orderId);
        }

        return "ok";
    }

    private WxPayOrderNotifyResult parseParams(HttpServletRequest request) {

        // V2接口回调
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(xmlResult)) {
            return null;
        }

        log.info("xmlResult=" + xmlResult);
        WxPayOrderNotifyResult result = WxPayOrderNotifyResult.fromXML(xmlResult);
        return result;

//        WxPayRefundNotifyResult.fromXML()

    }

//    private WxPayRefundNotifyResult parseParams(HttpServletRequest request) {
//
//        // V2接口回调
//        String xmlResult = null;
//        try {
//            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if (StringUtils.isEmpty(xmlResult)) {
//            return null;
//        }
//
//        log.info("xmlResult=" + xmlResult);
//        WxPayRefundNotifyResult result = WxPayRefundNotifyResult.fromXML(xmlResult);
//        return result;
//
////        WxPayRefundNotifyResult.fromXML()
//
//    }

}
